package com.wudizaba.pg.typeHandler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

@MappedJdbcTypes(JdbcType.ARRAY) // 指定对应的JDBC类型
@MappedTypes(Integer[].class) // 指定对应的Java类型
public class IntegerArrayTypeHandler extends BaseTypeHandler<Integer[]> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Integer[] integers, JdbcType jdbcType) throws SQLException {
        String arrayAsString = Arrays.toString(integers);
        preparedStatement.setString(i, arrayAsString);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String arrayAsString = resultSet.getString(s);
        return stringToArray(arrayAsString);
    }

    @Override
    public Integer[] getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String arrayAsString = resultSet.getString(i);
        return stringToArray(arrayAsString);
    }

    @Override
    public Integer[] getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        // 从CallableStatement中获取字符串并转换回数组
        String arrayAsString = callableStatement.getString(i);
        return stringToArray(arrayAsString);
    }

    private Integer[] stringToArray(String arrayAsString) {
        // 如果为null或者长度为0，返回null或空数组
        if (arrayAsString == null || arrayAsString.isEmpty()) {
            return new Integer[0];
        }
        // 将字符串按逗号分隔并转换为Integer数组
        return Arrays.stream(arrayAsString.substring(1, arrayAsString.length() - 1).split(", "))
                     .map(s -> Integer.valueOf(s.trim()))
                     .toArray(Integer[]::new);
    }
}